package cn.darkhorse.device.service.impl;

import cn.darkhorse.device.pojo.IotInstructParams;
import cn.darkhorse.device.mapper.IotInstructParamsMapper;
import cn.darkhorse.device.service.IotInstructParamsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.MqttClientConfig;
import com.ruoyi.common.config.MqttPusher;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangtianqi
 * @since 2024-10-22
 */
@Service
public class IotInstructParamsServiceImpl extends ServiceImpl<IotInstructParamsMapper, IotInstructParams> implements IotInstructParamsService {

    @Autowired
    private MqttClientConfig mqttClientConfig;
    @Override
    public boolean doPush(Long id) {
        IotInstructParams params = getById(id);
        if (params == null){
            throw new RuntimeException("指令不存在");
        }
        String topic = params.getTopic();
        String msg = params.getMessage();
        byte[] array;
        try {
            array = hexStringToByteArray(msg);
        } catch (Exception e) {
            throw new RuntimeException("报文格式异常,请输入正常的16进制报文");
        }

        try {
            MqttPusher.pushHex(mqttClientConfig,topic, array);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 将16进制字符串转换为字节数组
     * @param s
     * @return
     */
    public static byte[] hexStringToByteArray(String s) throws Exception {
        s = s.replaceAll(" ", ""); // 去掉空格
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}
